import numpy as np


# 定义一个包含正向和反向传播的类
class network:
    # 初始化参数
    def __init__(self, w, b):
        self.w = w
        self.b = b
        self.x = None
        self.dw = None
        self.db = None

    # 定义正向传播函数
    def forward(self, x):
        self.x = x
        y = np.dot(x, self.w) + self.b
        return y

    # 定义反向传播函数
    def backward(self, l):
        dx = np.dot(l, self.w.T)
        dw = np.dot(np.expand_dims(self.x.T, axis=1), l)
        db = np.sum(l, axis=0)
        return dw, db


# 定义输入数据
X = np.array([1.0, 1.5, 0.5])
# 初始化权重, w1 为3*4矩阵
W = np.array([[0.1, 0.2, 0.3, 0.4], [0.2, 0.5, 0.1, 0.3], [0.3, 0.4, 0.2, 0.1]])
# 定义B1偏移量
B = np.array([0.1, 0.2, 0.3, 0.4])
# 实例化network类
nt = network(W, B)
print(nt.forward(X))  # 计算正向传播输出值
L = np.array([[0.21, 0.15, 0.05, 0.45]])
dw, db = nt.backward(L)
print("dw:",dw)
print("db:", db)
# [0.65 1.35 0.85 1.3 ]
# dw: [[0.21  0.15  0.05  0.45 ]
# [0.315 0.225 0.075 0.675]
# [0.105 0.075 0.025 0.225]]
# db: [0.21 0.15 0.05 0.45]